package com.whfc.ms.websocket;

import com.whfc.common.util.JSONUtil;
import com.whfc.common.util.SessionAttr;
import com.whfc.entity.dto.msg.PushMsgDTO;
import com.whfc.fuum.entity.SysUser;
import com.whfc.ms.redis.StashMsMsgRedisDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.PongMessage;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.List;

/**
 * @author xugouhceng
 * @desc WebSocket事件处理
 */
@Component
public class TextMsgWebSocketHandler extends TextWebSocketHandler {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private static final String PING = "ping";

    private static final String PONG = "pong";

    @Autowired
    private WebSocketSessionManager sessionManager;

    @Autowired
    private StashMsMsgRedisDao stashMsgRedisDao;

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        SysUser loginUser = (SysUser) session.getAttributes().get(SessionAttr.MS_USER);
        String userId = String.valueOf(loginUser.getId());
        logger.info("ws,建立连接,loginUser:{}", userId, session);
        sessionManager.addSession(userId, session);
        //将暂存队列中的消息消费掉
        List<PushMsgDTO> stashMsgList = stashMsgRedisDao.getStashMsg(loginUser.getId());
        // List<List<PushMsgDTO>> lists = ListUtil.splitList(stashMsgList, 10);
        if (stashMsgList != null && stashMsgList.size() > 0) {
            for (PushMsgDTO pushMsgDTO : stashMsgList) {
                String textMsg = JSONUtil.toString(pushMsgDTO);
                session.sendMessage(new TextMessage(textMsg));
                logger.info("ms|ws,推送暂存消息:{}", JSONUtil.toString(textMsg));
            }
        }
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        SysUser loginUser = (SysUser) session.getAttributes().get(SessionAttr.MS_USER);
        String userId = String.valueOf(loginUser.getId());
        logger.info("ws,关闭连接,loginUser:{},session:{},status:{}", userId, session, status);
        sessionManager.closeSession(userId);
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        SysUser loginUser = (SysUser) session.getAttributes().get(SessionAttr.MS_USER);
        String userId = String.valueOf(loginUser.getId());
        logger.warn("ws,出现异常,loginName:{},session:{},exception:{}", userId, session, exception.getMessage());
        sessionManager.closeSession(userId);

    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        SysUser loginUser = (SysUser) session.getAttributes().get(SessionAttr.MS_USER);
        String userId = String.valueOf(loginUser.getId());
        logger.debug("ws,收到消息,userId:{},message:{}", userId, message.getPayload());
        if (PING.equalsIgnoreCase(message.getPayload())) {
            if (session.isOpen()) {
                session.sendMessage(new PongMessage());
            }
        }
    }
}
